package com.dgut.smart_house.withHardware;

import com.alibaba.fastjson.JSON;
import com.dgut.smart_house.config.WebsocketServer;
import com.dgut.smart_house.domain.*;
import com.dgut.smart_house.mapper.*;
import com.dgut.smart_house.util.MailUtil;
import org.apache.commons.collections.map.HashedMap;

import java.io.IOException;
import java.math.BigInteger;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class DataHandling {

    //    @Autowired
//    static DeviceMapper deviceMapper;
    private static DeviceMapper deviceMapper = (DeviceMapper) AppBean.getBean("deviceMapper");
    //    @Autowired
    static Datas data;

    static {
        data = new Datas();
    }

    //    @Autowired
//    static DatasMapper datasMapper;
    private static DatasMapper datasMapper = (DatasMapper) AppBean.getBean("datasMapper");

    //    @Autowired
//    static TypeMapper typeMapper;
    private static TypeMapper typeMapper = (TypeMapper) AppBean.getBean("typeMapper");

    //    @Autowired
//    static HandleMapper handleMapper;
    private static HandleMapper handleMapper = (HandleMapper) AppBean.getBean("handleMapper");

    //    @Autowired
//    static KeyCardMapper keyCardMapper;
    private static KeyCardMapper keyCardMapper = (KeyCardMapper) AppBean.getBean("keyCardMapper");

    private static UserMapper userMapper = (UserMapper) AppBean.getBean("userMapper");

    private static NodeMapper nodeMapper = (NodeMapper) AppBean.getBean("nodeMapper");

    private static WebsocketServer websocketServer = (WebsocketServer) AppBean.getBean("websocketServer");


    static public final int KeyDoorTypeId = 6;
    static public final int TemSensitiveTypeId = 8;
    static public final int TemWetNodeId = 8;


    public static void handling(String command, String MsgData) {

        List<Device> device = deviceMapper.findByCommand(command);
        float result = 0f;

        if (device.size() == 0) {
            device = deviceMapper.findByCommand(command.replaceAll("0x", "0x0").replaceAll("0X", "0X0"));
            if (device.size() == 0) {
                return;
            }
        }

        if (device.size() > 1) {
            /**
             * 如果是温湿度传感器
             */
            if (device.get(0).getNodeId() == TemWetNodeId) {
                //过滤硬件端的初始数据
                if(MsgData.length()!=8){
                    return;
                }

                float wet = Float.valueOf(new BigInteger(MsgData.substring(0, 2), 16).toString(10) + '.' + new BigInteger(MsgData.substring(2, 4), 16).toString(10));
                float tem = Float.valueOf(new BigInteger(MsgData.substring(4, 6), 16).toString(10) + '.' + new BigInteger(MsgData.substring(6, 8), 16).toString(10));
                data.setDevId(device.get(0).getDevId());
                data.setFromUser(device.get(0).getFromUser());
                data.setType(device.get(0).getTypeId());
                data.setNode(device.get(0).getNodeId());
                data.setAcceptTime(new Date(System.currentTimeMillis()));
                data.setValue(device.get(0).getTypeId() == TemSensitiveTypeId ? tem : wet);
                try {
                    WebsocketServer.sendInfo(JSON.toJSONString(data), device.get(0).getFromUser());
                    datasMapper.createData(data);

                    data.setDevId(device.get(1).getDevId());
                    data.setValue(device.get(1).getTypeId() == TemSensitiveTypeId ? tem : wet);
                    data.setType(device.get(1).getTypeId());

                    WebsocketServer.sendInfo(JSON.toJSONString(data), device.get(0).getFromUser());
                    datasMapper.createData(data);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        } else {
            if (device.get(0).getNodeId() == KeyDoorTypeId) {
                //接收新增门卡信息
                if (keyCardMapper.findNewAddCard(device.get(0).getFromUser()) != null) {
                    long keyCard=Long.parseLong(MsgData,16);
                    int devUser=device.get(0).getFromUser();
                    //卡号已经存在
                    if(keyCardMapper.findCardByCardId(keyCard)!=null){
                        keyCardMapper.deleteNewAddCard(devUser);
                        try {
                            WebsocketServer.sendInfo("CreateCardERROR", device.get(0).getFromUser());
                            return;
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    try{
                    keyCardMapper.updateNewAddCard(keyCard,devUser );
                    WebsocketServer.sendInfo("CreateCardSUCCESS", device.get(0).getFromUser());
                    }catch (Exception e){
                        keyCardMapper.deleteNewAddCard(devUser);
                        try {
                            WebsocketServer.sendInfo("CreateCardERROR", device.get(0).getFromUser());
                        } catch (IOException e1) {
                            e1.printStackTrace();
                        }
                        System.out.println(e);
                    }
                }
            } else {
                Device device1 = device.get(0);
                float Msgdata = Float.valueOf(MsgData);
                Types type = typeMapper.findByTypeId(device1.getTypeId());


                if (type.getMaxNum() < Msgdata) {
                    Handle handle1 = handleMapper.findHandleBydeviceIdIfStateIsZero(device1.getDevId());

                    //每60秒提醒一次
                    if (handle1 != null && (System.currentTimeMillis() - handle1.getExceptionDate().getTime()) % 70000 >= 60000) {
                        handle1.setExceptionNum(handle1.getExceptionNum() + 1);
                        //websocket提醒
                        try {
                            WebsocketServer.sendInfo("Warn", device1.getFromUser());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    } else if (handle1 == null) {
                        Handle handle = new Handle();
                        //fromUser,deviceId,nodeId,typeId
                        handle.setFromUser(device1.getFromUser());
                        handle.setDeviceId(device1.getDevId());
                        handle.setNodeId(device1.getNodeId());
                        handle.setTypeId(device1.getTypeId());
                        handleMapper.generateHandle(handle);

                        try {
                            websocketServer.sendInfo("Warn", device1.getFromUser());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                        /**
                         * 邮件通知
                         */
                        User user = userMapper.findById(device1.getFromUser());
                        Node node = nodeMapper.findByNodeId(device1.getNodeId());
                        Map map = new HashedMap();
                        map.put("userId", user.getUserId());
                        map.put("desc", device1.getDevDesc());
                        map.put("node", node.getNodeName());
                        map.put("email", user.getEmail());
                        MailUtil mailUtil = new MailUtil();
                        mailUtil.sendMail(map);

                    }
                }
                data.setDevId(device1.getDevId());
                data.setFromUser(device1.getFromUser());
                data.setType(device1.getTypeId());
                data.setNode(device1.getNodeId());
                data.setValue(Msgdata);
                data.setAcceptTime(new Date(System.currentTimeMillis()));
                datasMapper.createData(data);
                try {
                    WebsocketServer.sendInfo(JSON.toJSONString(data), device.get(0).getFromUser());
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }


    }
}
/*

        Types type = typeMapper.findByTypeId(device.getTypeId());
        if (type.getMaxNum() <= Float.valueOf(str[1])) {
            Handle handle1=handleMapper.findHandleBydeviceIdIfStateIsZero(devId);

            //每30秒提醒一次
            if (handle1!=null&&(System.currentTimeMillis()-handle1.getExceptionDate().getTime())%30000==0){
                handle1.setExceptionNum(handle1.getExceptionNum()+1);
                //websocket提醒
                //TODO
            }else {
            Handle handle=new Handle();
            //fromUser,deviceId,nodeId,typeId
            handle.setFromUser(device.getFromUser());
            handle.setDeviceId(devId);
            handle.setNodeId(device.getNodeId());
            handle.setTypeId(device.getTypeId());
            handleMapper.generateHandle(handle);
            }
        } else {
            data.setDevId(devId);
            data.setFromUser(device.getFromUser());
            data.setType(device.getTypeId());
            data.setNode(device.getNodeId());
            data.setValue(Float.valueOf(str[1]));
            try {
                WebsocketServer.sendInfo(data.toString(),device.getFromUser());
            } catch (IOException e) {
                e.printStackTrace();
            }
            datasMapper.createData(data);
        }

 */
